package model

import (
	"database/sql"
	"errors"
	"github.com/jmoiron/sqlx"
	"zimuzu_cvn_web_api/config"
	. "zimuzu_cvn_web_api/pkg/e"
)

type AdminUserDb struct {
	Id         int64  `db:"id"`
	Account    string `db:"account"`
	Salt       string `db:"salt"`
	Pwd        string `db:"pwd"`
	CreateTime int64  `db:"create_time"`
	NickName   string `db:"nick_name"`
	Type   int `db:"type"`
	Status   int `db:"status"`
}

//通过手机号查询账号信息
//Auth: Xu
func GetAdminUserByMobile(db sqlx.Queryer, mobile string) (AdminUserDb, error) {
	var user AdminUserDb
	err := sqlx.Get(db, &user, `select id,account,pwd,salt,nick_name from admin_user where account = ? limit 1`, mobile)
	if err == sql.ErrNoRows {
		return user, errors.New("账号信息不存在")
	}
	if err != nil {
		Log("err", mobile, ":获取账号信息失败")
		return user, err
	}

	return user, nil
}

//通过手机号查询账号信息
//Auth: Xu
func GetAdminUserByUid(db sqlx.Queryer, uid int64) (AdminUserDb, error) {
	var user AdminUserDb
	err := sqlx.Get(db, &user, `select id,account,pwd,salt,nick_name,type from admin_user where id = ? limit 1`, uid)
	if err == sql.ErrNoRows {
		return user, errors.New("账号信息不存在")
	}
	if err != nil {
		Log("err", ":获取账号信息失败")
		return user, err
	}

	return user, nil
}

//添加后台管理员信息
//Auth:Xu
func CreateAdminUser(db sqlx.Execer, user AdminUserDb) (int64, error) {
	var re sql.Result
	re = sqlx.MustExec(db, `INSERT INTO admin_user (account, nick_name, pwd, salt, create_time) 
VALUES (?, ?, ?, ?, ?)`,
		user.Account, user.NickName, user.Pwd, user.Salt, user.CreateTime)
	uid, err := re.LastInsertId()
	if err != nil {
		return 0, err
	}

	return uid, nil
}

//修改管理员状态
//Auth:Xu
func DeleteAdminUser(db sqlx.Execer, id int64) ( error) {
	var re sql.Result
	re = sqlx.MustExec(db, `update admin_user set status = 2 where id = ?`, id)
	num, err := re.RowsAffected()
	if err != nil{
		return  err
	}
	if num == 0{
		return errors.New("删除管理员失败")
	}

	return nil
}


type AdminUserList struct {
	Id         int64  `db:"id" json:"id"`
	Phone    string `db:"account" json:"phone"`
	CreateTime string  `db:"create_time" json:"createTime"`
	NickName   string `db:"nick_name" json:"nickname"`
}
//查询管理员列表
//Auth:Xu
func GetAdminList()(res []AdminUserList, err error){
	err = sqlx.Select(config.C.DB.DB, &res, "SELECT id,account,nick_name, from_unixtime(create_time, '%Y/%m/%d') create_time FROM"+
		" admin_user WHERE `status` = 1")
	if err != nil {
		return res, err
	}
	return res, nil
}


